/*
 * @Date: 2025-07-20 21:37:43
 * @LastEditTime: 2025-07-24 23:32:35
 */
import axios from "axios";
import type {
  InternalAxiosRequestConfig,
  AxiosResponse,
  AxiosError,
} from "axios";
import { ElMessageBox } from "element-plus";

// 是否是开发环境
const isDev = process.env.NODE_ENV === "development";

const instance = axios.create({
  // baseURL: "https://immichat.top",
  //http://124.70.73.99
  baseURL: isDev ? "/api" : "https://buddy-meow.com/buddymeow/",
  timeout: 1000 * 60 * 60,
  withCredentials: true, // 跨域请求时需要使用凭证
});

/* 获取Store信息 */
// const store = useAccountStore();

// http request 拦截器
instance.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const url = config.url as string;
    const headers = config.headers || {};
    headers["Content-Type"] = "application/json;charset=utf-8";
    headers["X-Requested-With"] = "XMLHttpRequest";
    config.headers = headers;
    // 兼容IE 防止请求缓存，增加时间戳
    config.url +=
      (url.indexOf("?") > -1 ? "&" : "?") + "_t=" + new Date().getTime();
    return config;
  },
  (err: any) => {
    return Promise.reject(err);
  }
);

// http response 拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) =>
    new Promise((resolve) => {
      resolve(response);
    }),
  (error: AxiosError<any>) => {
    const { code, response } = error;
    if (code === "ERR_NETWORK") {
      ElMessageBox({
        title: "提示",
        message: "ERR_NETWORK，请确认网络连接是否正常！",
        confirmButtonText: "再试一次",
      }).then(() => {
        window.location.reload();
      });
    } else if (response) {
      switch (response.status) {
        case 404:
          ElMessageBox({
            title: "提示",
            message: "访问的资源不存在！",
            confirmButtonText: "再试一次",
          }).then(() => {
            window.location.reload();
          });
          break;
        case 405:
          ElMessageBox({
            title: "提示",
            message: "接口参数有误！",
            confirmButtonText: "再试一次",
          }).then(() => {
            window.location.reload();
          });
          break;
        case 500:
          ElMessageBox({
            title: "提示",
            message: "服务异常，请稍后再试！",
            confirmButtonText: "再试一次",
          }).then(() => {
            window.location.reload();
          });
          break;
        default:
          ElMessageBox({
            title: "提示",
            message: response.data.success,
          }).then(() => {});
      }
    }
    return Promise.reject(error);
  }
);

export default instance;
